# -*- coding: utf-8 -*-
import json

from flask import Blueprint, render_template, request, jsonify, make_response, current_app, redirect, url_for, g

from application import db, app
from common.libs.UserSerivice import UserService
from common.libs.render_helper import ops_render
from web.models.user import User

route_user = Blueprint('user_page', __name__)

@route_user.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("user/login.html")
    else:
        # 设置resp对象来定义返回的值
        resp = {"code": 200, "msg": "登录成功", "data": {}}
        req = request.values
        login_name = req["login_name"] if "login_name" in req else ""
        login_pwd = req["login_pwd"] if "login_pwd" in req else ""
        if (not login_name) or len(login_name) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的登录用户名"
            return jsonify(resp)
        if (not login_pwd) or len(login_pwd) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的密码"
            return jsonify(resp)

        # 使用模型验证用户名和密码
        user_info = User.query.filter_by(login_name=login_name).first()
        if not user_info:  # 数据库查不到
            resp["code"] = -1
            resp["msg"] = "请输入正确的用户名或密码"
            return jsonify(resp)

        # 密码加盐值
        salt = user_info.login_salt
        gen_pwd2 = UserService.gen_pwd(login_pwd, salt)  # 跟注册时相同的加密机制
        # print('md5加密加盐的16进制值（32位16进制）：', gen_pwd2)

        if user_info.login_pwd != gen_pwd2:
            resp["code"] = -1
            resp["msg"] = "请输入正确的用户名或密码"
            return jsonify(resp)

        # 登录成功
        resp['data']['username'] = login_name
        resp['data']['password'] = login_pwd
        resp['data']['salt'] = salt
        # 因为jsonify无法携带cookie，所以构造response对象把字典转换成json字符串
        # return jsonify(resp)
        response = make_response(json.dumps(resp))
        # 携带cookie，加密cookie
        cokie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
        # current_app.config.get()获取到cookie的字段和值
        # set_cookie函数是由服务器发送一个HTTP-cookie到浏览器
        response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cokie_str)
        return response

# 登出操作
@route_user.route("/logout")
def logout():
    response = redirect(url_for('user_page.login'))
    response.delete_cookie(current_app.config['AUTH_COOKIE_NAME'])
    return response

@route_user.route("/edit", methods=['GET', 'POST'])
def edit():
    # return render_template("user/edit.html")
    if request.method == 'GET':
        '''get请求时渲染页面'''
        return ops_render('user/edit.html')

    if request.method == 'POST':
        '''修改姓名和邮箱时发送post请求，修改数据库记录'''
        resp = {"code": 200, "msg": "操作成功", "data": {}}
        req = request.values
        nickname = req["nickname"] if "nickname" in req else ""
        email = req["email"] if "email" in req else ""

        # 验证输入合法逻辑
        if (not nickname) or len(nickname) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的姓名"
            return jsonify(resp)
        if (not email) or len(email) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的邮箱"
            return jsonify(resp)

        # 把更改后的当前用户信息更新到数据库中
        user_info = g.current_user
        user_info.nickname = nickname
        user_info.email = email
        db.session.add(user_info)
        db.session.commit()  # 事务提交

        return jsonify(resp)


@route_user.route("/reset-pwd", methods=['GET', 'POST'])
def resetPwd():
    # return render_template("user/reset_pwd.html")
    if request.method == 'GET':
        '''get请求时渲染页面'''
        return ops_render('user/reset_pwd.html')

    if request.method == 'POST':
        resp = {"code": 200, "msg": "修改密码成功", "data": {}}
        # 获取请求参数
        req = request.values
        old_password = req["old_password"] if "old_password" in req else ""
        new_password = req["new_password"] if "new_password" in req else ""

        # 验证输入合法逻辑
        if (not old_password) or len(old_password) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的原密码"
            return jsonify(resp)
        if (not new_password) or len(new_password) < 6:
            resp["code"] = -1
            resp["msg"] = "请输入不少于6位的新密码"
            return jsonify(resp)
        if old_password == new_password:
            resp["code"] = -1
            resp["msg"] = "新旧密码一致"
            return jsonify(resp)

        # 验证旧密码是否和登录时候的用户密码一致
        user_info = g.current_user
        salt = user_info.login_salt
        gen_pwd = UserService.gen_pwd(old_password, salt)  # 跟注册时相同的加密机制
        if user_info.login_pwd != gen_pwd:
            resp["code"] = -1
            resp["msg"] = "原密码不对~"
            return jsonify(resp)

        # 更新新的密码到数据库
        user_info.login_pwd = UserService.gen_pwd(new_password, salt)
        # 提交事务到数据库
        db.session.add(user_info)
        db.session.commit()

        # 更新cookie，否则页面信息验证失败无法跳转到其他页面
        # 3.生成新的cookie
        response = make_response(json.dumps(resp))
        # 携带cookie
        cokie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
        response.set_cookie(app.config.get("AUTH_COOKIE_NAME"), cokie_str, max_age=7 * 24 * 60 * 60)
        return response